package db

import (
	"database/sql/driver"
	"distributed-locks/lib/config"
	"encoding/json"
	"errors"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"time"
)

var (
	db *gorm.DB
)

func createDB(username string, password string, host string, port int64, database string) *gorm.DB {
	//dsn := "gjf:123456@tcp(121.4.213.43:3306)/gjf?charset=utf8mb4&parseTime=True&loc=Local"
	dsn := fmt.Sprintf(
		"%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		username,
		password,
		host,
		port,
		database,
	)
	// 配置日志
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer（日志输出的目标，前缀和日志包含的内容——译者注）
		logger.Config{
			SlowThreshold:             time.Second,   // 慢 SQL 阈值
			LogLevel:                  logger.Silent, // 日志级别
			IgnoreRecordNotFoundError: true,          // 忽略ErrRecordNotFound（记录未找到）错误
			Colorful:                  false,         // 禁用彩色打印
		},
	)
	_dbConnect, err := gorm.Open(
		mysql.Open(dsn),
		&gorm.Config{
			NamingStrategy: schema.NamingStrategy{
				SingularTable: true, // 禁用创建表名复数带 s
				TablePrefix:   "",   // 统一表前缀, 自定义表名会覆盖全局
			},
			//DisableForeignKeyConstraintWhenMigrating: true, // AutoMigrate 会自动创建数据库外键约束，您可以在初始化时禁用此功能
			Logger: newLogger,
		})
	if err != nil {
		panic("failed to connect database")
	}
	return _dbConnect
}

// GormList, 在 Gorm 中之定义数据类型
type GormList []interface{}

// 往数据库插入值，做逻辑转换
// Value 实现 driver.Valuer 接口，Value 返回 json value
func (j GormList) Value() (driver.Value, error) {
	if len(j) == 0 {
		return nil, nil
	}
	return json.Marshal(j)
}

// 从数据库读取值，做逻辑转换
// Scan 实现 sql.Scanner 接口，Scan 将 value 扫描至 Jsonb
func (j *GormList) Scan(value interface{}) error {
	bytes, ok := value.([]byte) // 断言转换成 []byte 类型
	if !ok {
		return errors.New(fmt.Sprint("Failed to unmarshal JSONB value:", value))
	}
	err := json.Unmarshal(bytes, j)
	return err
}

func init() {
	db = createDB(config.DB_W_username, config.DB_W_password, config.DB_W_host, config.DB_W_port, config.DB_W_database)
}

func GetDB() *gorm.DB {
	return db.Debug()
}
